'use strict';

const { DataTypes } = require('sequelize');

/**
 * WhatsApp会话模型，记录用户的WhatsApp连接状态和会话信息
 * @param {import('sequelize').Sequelize} sequelize Sequelize实例
 */
module.exports = (sequelize) => {
  const WhatsAppSession = sequelize.define('WhatsAppSession', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'users',
        key: 'id'
      }
    },
    sessionId: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: 'WhatsApp会话唯一标识符'
    },
    status: {
      type: DataTypes.ENUM('disconnected', 'connecting', 'connected'),
      allowNull: false,
      defaultValue: 'disconnected'
    },
    startTime: {
      type: DataTypes.DATE,
      allowNull: false,
      comment: '会话开始时间'
    },
    endTime: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '会话结束时间'
    },
    duration: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: '会话持续时间，单位为秒'
    },
    phoneNumber: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: '关联的WhatsApp手机号码'
    },
    deviceInfo: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: 'WhatsApp设备信息'
    },
    loginDeviceType: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: '登录设备类型'
    },
    batteryLevel: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: '设备电池电量'
    },
    messageCount: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '会话期间消息总数'
    },
    contactCount: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '会话期间互动的联系人数量'
    },
    lastActivityTime: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '最后活动时间'
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false
    }
  }, {
    tableName: 'whatsapp_sessions',
    timestamps: true,
    indexes: [
      {
        fields: ['userId']
      },
      {
        fields: ['sessionId']
      },
      {
        fields: ['status']
      },
      {
        fields: ['startTime']
      }
    ]
  });

  // 添加关联
  WhatsAppSession.associate = (models) => {
    WhatsAppSession.belongsTo(models.User, {
      foreignKey: 'userId',
      as: 'user'
    });
  };

  return WhatsAppSession;
}; 